import {Component, ViewChild} from '@angular/core';
import {
  IonicPage,
  ModalController,
  Navbar,
  NavController,
  NavParams,
  PopoverController,
} from 'ionic-angular';
import {DialogProvider} from "@providers/dialog";
import {StorageProvider} from "@providers/storage";
import {NativeProvider} from "@providers/natives/native";
import {WorkerProvider} from "@providers/interface/worker";
import {Observable} from "rxjs/Observable";
import {Util} from "@providers/util";
import {ImagePickerObject} from "@common/ImagePickerObject";
import {ImageManipulationProvider} from "@providers/interface/image-manipulation";

@IonicPage()
@Component({
  selector: 'page-worker-look-finish-repair',
  templateUrl: 'worker-look-finish-repair.html',
})
export class WorkerLookFinishRepairPage {

  @ViewChild(Navbar) navbar: Navbar;
  picList: any[] = []; //手机选择的图片
  upPicList: any[] = []; //已经上传的图片
  userInfo: any = this.storageService.read("userInfo");
  codeList: any[] = [];
  bz: string = "";//备注
  //因为故障原因和维修措施数据量较少，因此可以提前加载，防止连续操作时卡顿
  faultCause: any[] = [];//故障原因
  cacheFaultCause: any;
  maintenancemMeasures: Map<any, any[]> = new Map<any, any[]>();//维修措施
  maintenancemMeasuresByFaultCause: any[] = [];
  WXCS: any;//維修措施
  safe: any;//保内保外
  param = JSON.parse(JSON.stringify(this.navParam.data));
  costs: any[] = [];//费用列表
  fixedCosts: any[] = [];//固定费用
  materialCosts: any[] = [];//辅材费用
  diyCosts: any[] = [];//自定义费用
  privateCosts: any[] = [];//自费辅材费用列
  guaranteeCosts: any[] = [];//保修辅材费用列
  sum: any = 0;//费用总价
  guaranteeSum: any = 0;//保修辅材费用总价
  cacheOrder: any;//缓存的已完工订单
  guarantee: any;//保内保外类型

  isPJHS: boolean = false; //是否需要配件回收
  CQTP;
  SP;
  isApp;

  addCode = false;

  settlementObjects;
  salesMethods;

  run: any[] = [];//next方法是否调用
  num: number;//计数器

  SPLB: any = this.navParam.data.CSM_SORDERITEM;//商品列表

  constructor(private navParam: NavParams,
              private dialog: DialogProvider,
              private modalCtrl: ModalController,
              private storageService: StorageProvider,
              private native: NativeProvider,
              private worker: WorkerProvider,
              private navCtrl: NavController,
              private popoverCtrl: PopoverController,
              private imageMpn: ImageManipulationProvider,) {
  }

  push(page: string, data?: any) {
    this.navCtrl.push(page, data);
  }

  ionViewDidLoad() {
    // Util.replaceBackButtonEvent(this.navbar, this.navCtrl, this.events);
    this.init();
  }

  /**
   * 初始化数据
   */
  init() {
    this.isApp = this.native.isCordova;
    this.bz = this.param.BZ;
    this.imagedowablelode();
    this.worker.getNJMSFBT().then(message => {
      let data = JSON.parse(JSON.stringify(message))['data'];
      if (!Util.isNull(data)) {
        this.addCode = data[0].ID === '1';
      } else {
        this.addCode = false;
      }
    }).then(() => {
      this.nnext(0);
    }).catch(error => {

      this.nnext(0);
      console.log(error);
    });
    this.getfixedCosts();
    this.getSPMC();
    this.initCacheOrder();
    if (this.userInfo.GSCS === '5') {
      this.getSettlementObjects();
      this.getSalesMethods();
    }
    if (this.param.DESCRIPTION == '维修') {
      this.getFaultCause();
      this.cacheFaultCause = this.param.GZLX||'';
      this.loadMaintenancemMeasuresByFaultCause(this.cacheFaultCause);
      this.WXCS = this.param.WXCS||'';
    }
  }

  /**
   * 初始化缓存的已完工订单
   */
  initCacheOrder() {
    /*this.cacheOrder = this.storageService.read("cacheOrder");
     if (Util.isNull(this.cacheOrder)){*/
    this.cacheOrder = {
      "id": this.param.ID,//单号
      "signer": this.userInfo.PARTYID,
      "splist": [],// id、skuid、codeList、bz、costs、picture
    }
    // }
  }


  /*showCostModal() {
    let modal = this.modalCtrl.create('CostPage', {
      "fixedCosts": this.fixedCosts,
      "diyCosts": this.diyCosts,
      "materialCosts": this.materialCosts,
      "guaranteeCosts": this.guaranteeCosts,
      "product_id": this.param.SP.SKUID,
      "SERVICETYPEID": this.param.SERVICETYPEID
    });
    modal.onDidDismiss(data => {
      if (data) {
        this.fixedCosts = data.fixedCosts;
        this.diyCosts = data.diyCosts;
        this.materialCosts = data.materialCosts;
        this.guaranteeCosts = data.guaranteeCosts;
      }
      this.formateData();
    });
    modal.present();
  }*/

  isDragBackTheOldThing() {
    for (let i = 0; i < this.costs.length; i++) {
      if (this.costs[i]["isPJHS"]) {
        this.costs[i]["JJTHBJ"] = 1;
      } else {
        this.costs[i]["JJTHBJ"] = 0;
      }
    }
  }

  /**
   * 合并费用列表，计算总费用
   */
  formateData() {
    this.privateCosts = this.fixedCosts.concat(this.materialCosts, this.diyCosts);
    this.sum = 0;
    this.guaranteeSum = 0;
    for (let i = 0; i < this.privateCosts.length; i++) {
      this.privateCosts[i]['BXLX'] = 1;
    }
    for (let i = 0; i < this.guaranteeCosts.length; i++) {
      this.guaranteeCosts[i]['BXLX'] = 0;
    }
    this.costs = this.guaranteeCosts.concat(this.privateCosts);
    for (let i = 0; i < this.costs.length; i++) {
      if (this.costs[i]['BXLX'] == 1) {
        this.sum += +(this.costs[i]['PRICE'] * this.costs[i]['QUANTITY']).toFixed(2);
      }
      if (this.costs[i]['BXLX'] == 0) {
        this.guaranteeSum += +(this.costs[i]['PRICE'] * this.costs[i]['QUANTITY']).toFixed(2);
      }
    }
    /*this.costs.forEach(value => {
        this.sum += value.PRICE * value.QUANTITY;
    });*/
  }

  /**
   * 获取固定费用
   */
  getfixedCosts() {
    this.worker.getFCFLSP({
      "SPID": this.param.SP.SKUID
    }).then(v => {
      this.fixedCosts = v.data;
      this.fixedCosts.forEach(value => {
        value.QUANTITY = 1;
      });
      this.formateData();
    }).catch(e => {
      this.dialog.showAlert("请检查网络");
    })
  }

  //上传图片
  uploadImage(): Observable<any> {
    return Observable.create((observer) => {
      if (this.picList.length > 0) {
        this.dialog.showLoading();
        this.native.uploadImageFile(this.picList).subscribe(res => {
          // this.dialog.hideLoading();
          this.upPicList = res;
          observer.next(true);
        })
      } else {
        observer.next(true);
      }
    })
  }

  submit() {
    console.log(this.picList)
    let _next = () => {
      let sp = {};//商品，id、skuid、codeList、bz、costs、picture
      sp["id"] = this.param.ID;
      sp["skuid"] = this.param.SP.SKUID;
      sp["line"] = this.param.SP.LINE;
      sp["codeList"] = [];//内外机编码列表
      console.log(this)
      for (let i = 0; i < this.codeList.length; i++) {
        let spcode: any[] = this.codeList[i]["codes"];
        if ((!spcode[1].code) && this.addCode) {
          this.dialog.showAlert("请填写内机编码");
          this.dialog.hideLoading();
          return;
        }
        for (let j = 0; j < spcode.length; j++) {
          let code: any = {};
          code["skuid"] = this.param.SP.SKUID;
          code["code"] = spcode[j].code;
          code["lx"] = spcode[j].lx;
          sp["codeList"].push(code);
        }
      }
      sp["bz"] = this.bz;
      sp["costs"] = this.costs.filter(value => {
        this.isDragBackTheOldThing();
        return value.QUANTITY > 0;
      });

      let pic: any[] = [];
      console.log(this)
      console.log(this.picList)
      for (let i = 0; i < this.picList.length; i++) {
        pic.push(this.picList[i]["url"])
      }
      sp["picture"] = pic.join(',');
      if (this.param.DESCRIPTION == '维修') {
        sp['gzyy'] = this.cacheFaultCause;
        let wxcss: string = "";
        for (let i = 0; i < this.maintenancemMeasuresByFaultCause.length; i++) {
          wxcss = wxcss + this.maintenancemMeasuresByFaultCause[i].WXCS;
          if (i != this.maintenancemMeasuresByFaultCause.length - 1) {
            wxcss += ",";
          }
        }
        console.log(wxcss);
        sp['wxcs'] = wxcss;
      }
      /*sp['guaranteeCosts'] = this.guaranteeCosts;*/
      this.cacheOrder.splist = this.cacheOrder.splist.filter(value => {
        return value.skuid != sp['skuid'] && value.line != sp['line']
      });
      this.cacheOrder.guarantee = this.safe;//保内保外类型
      this.cacheOrder.splist.push(sp);
      this.cacheOrder.sum = this.sum;
      this.cacheOrder.picture = pic.join(',');
      this.cacheOrder.bz = this.bz;

      let popover = this.popoverCtrl.create('RpayPage', this.cacheOrder, {cssClass: 'jl_mask'});
      popover.onDidDismiss((data) => {
        if (data) {
          this.navCtrl.pop();
        }
      });
      popover.present();
    };
    let modal = this.modalCtrl.create("SignaturePadPage");
    modal.onDidDismiss(_data => {
      if (Util.isNull(_data)) return;
      this.cacheOrder.CQTP = _data['imageData'];
      _next();
    });
    modal.present();
  }


  //回车增加编号栏事件
  shuRus(event, SP, i: any) {
    if (this.addCode) {
      if (!Util.isNull(SP.codes[1].code)) {
        if (Util.isNull(this.run[i])) {

          this.nnext(this.SPLB.length - SP.LINE);
          this.run.push(i);
        }
      }
    } else {
      if (Util.isNull(this.run[i])) {

        this.nnext(this.SPLB.length - SP.LINE);
        this.run.push(i);
      }
    }

  }

  //失去焦点增加编号栏事件
  sJs(v, SP, i) {
    if (!Util.isNull(v.code)) {
      if (this.addCode) {
        if (!Util.isNull(SP.codes[1].code)) {
          if (Util.isNull(this.run[i])) {

            this.nnext(this.SPLB.length - SP.LINE);
            this.run.push(i);
          }
        }
      } else {
        if (Util.isNull(this.run[i])) {

          this.nnext(this.SPLB.length - SP.LINE);
          this.run.push(i);
        }
      }
    }
  }


  /**
   * 增加一对机器编码
   */
  nnext(item: any) {
    //循环判断编号框是否大于商品数量
    let cd: any = 0;
    let cds: any = 0;
    let spnum: number = 0;
    for (let i = 0; i < this.SPLB.length; i++) {
      cd += this.SPLB[i]['NUM'];
    }
    for (let j = 0; j < this.codeList.length; j++) {
      if (this.codeList[j]['codes']['0']['lx'] == '1') {
        cds++;
        if (cds == cd) {
          return;
        }
      }
    }

    let code = this.codeList.filter(value => {
      return value.lx == '1' && value.code.trim() == '';
    });
    if (code.length > 0) {
      return;
    }

    for (let k = 0; k <=item; k++) {
      spnum = spnum + this.SPLB[k]['NUM'];
    }
    if (cds == 0) {
      this.num = 0;
    }else if(cds == spnum ){
      this.num = 0;
      item++;
    }
    let ary: any[];
    ary=this.initCode(this.SPLB[item]['codelist']);

    let a: any = Object.assign(JSON.parse(JSON.stringify(this.SPLB[item])), {codes: ary});

    if (item == 0 && this.codeList.length == 0) {
      this.codeList = [a];
    } else {
      this.codeList.push(a);
    }
  }

  /**
   * 初始化codes值
   */
  initCode(code) {
    let ary:any[]=[];
    let length: number;
    if (this.addCode) {
      length = 3;
    } else {
      length = 2;
    }
    for (let k = 0; k < length; k++) {
      if (ary.length == 0) {
        if (code[this.num]) {
          if (code[this.num]['TYPE'] == 1) {
            ary.push({
              "code": code[this.num]['CODE'],
              "lx": "1"
            });
            this.num++;
          } else {
            ary.push({
              "code": '',
              "lx": "1"
            });
          }
        } else {
          ary.push({
            "code": '',
            "lx": "1"
          });
        }
      } else if (ary.length == 1) {
        if (code[this.num]) {
          if (code[this.num]['TYPE'] == 2) {
            ary.push({
              "code": code[this.num]['CODE'],
              "lx": "2"
            });
            this.num++;
          } else {
            ary.push({
              "code": '',
              "lx": "2"
            });
          }
        } else {
          ary.push({
            "code": '',
            "lx": "2"
          });
        }
      } else if (ary.length == 2) {
        if (code[this.num]) {
          if (code[this.num]['TYPE'] == 3) {
            ary.push({
              "code": code[this.num]['CODE'],
              "lx": "3"
            });
            this.num++;
          } else {
            ary.push({
              "code": '',
              "lx": "3"
            });
          }
        } else {
          ary.push({
            "code": '',
            "lx": "3"
          });
        }
      }
    }
    return JSON.parse(JSON.stringify(ary));
  }

  /**
   * 扫一扫获取外机编码
   * @param vcode 编码
   * @param SP
   * @param i
   */
  scanWJBM(vcode: any, SP: any, i: any) {
    this.native.openScanner().then(v => {
      vcode.code = v;
      if (this.addCode) {
        if (!Util.isNull(SP.codes[1].code)) {
          if (Util.isNull(this.run[i])) {

            this.nnext(this.SPLB.length - SP.LINE);
            this.run.push(i);
          }
        }
      } else {
        if (Util.isNull(this.run[i])) {

          this.nnext(this.SPLB.length - SP.LINE);
          this.run.push(i);
        }
      }
    }).catch(e => console.log(e));
  }

  /**
   * 扫一扫获取内机编码
   * @param vcode 编码
   * @param SP
   * @param i
   */
  scanNJBM(vcode: any, SP: any, i: any) {
    this.native.openScanner().then(v => {
      vcode.code = v;
      if (this.addCode) {
        if (!Util.isNull(SP.codes[1].code)) {
          if (Util.isNull(this.run[i])) {

            this.nnext(this.SPLB.length - SP.LINE);
            this.run.push(i);
          }
        }
      } else {
        if (Util.isNull(this.run[i])) {

          this.nnext(this.SPLB.length - SP.LINE);
          this.run.push(i);
        }
      }
    }).catch(e => console.log(e));
  }

  getSPMC() {
    this.SP = this.param.CSM_SORDERITEM;
  }

  imagedowablelode() {
    this.imageMpn.imagedowablelode({ID: this.param.ID}).then(data => {
      let datas: any[] = data['data'];
      let files: ImagePickerObject[] = [];
      for (let i = 0; i < datas.length; i++) {
        let file = new ImagePickerObject();
        file.url = datas[i]['PICTURE'];
        file.id = datas[i]['XLH'];
        files.push(file);
      }
      this.picList = files
    }).catch(() => {
    });
  }

  delImage(event) {
    this.imageMpn.delImage({XLH: event[0].id}).then(() => {
      //this.imagedowablelode();
    }).catch(() => {
    });
  }

  imageUpload(event) {
    for (let i = 0; i < event.length; i++) {
      this.imageMpn.imageUpload({
        ID: this.param.ID,
        PICTURE: event[i].url
      }).then((data) => {
        event[i].id = data.message;
      }).catch((error) => {
      });
    }
  }

  showMaterialModal() {
    let modal = this.modalCtrl.create('WorkerLookMaterielPage',
      {
        "materialCosts": this.materialCosts,
        "product_id": this.param.SP.SKUID,
        "SERVICETYPEID": this.param.SERVICETYPEID
      });
    modal.onDidDismiss(data => {
      if (data) {
        this.materialCosts = data;
        let num: number = 0;
        for (let i = 0; i < this.materialCosts.length; i++) {
          num += this.materialCosts[i]['QUANTITY']
        }
        this.materialCosts["num"] = num;
        this.calculateSum();
        this.formateData();
      }
    });
    modal.present();
  }

  showGuaranteeMaterialModal() {
    let modal = this.modalCtrl.create('WorkerLookMaterielPage',
      {
        "materialCosts": this.guaranteeCosts,
        "product_id": this.param.SP.SKUID,
        "SERVICETYPEID": this.param.SERVICETYPEID,
        "BJ": 1
      });
    modal.onDidDismiss(data => {
      if (data) {
        Object.assign(this.guaranteeCosts, data);
        let num: number = 0;
        for (let i = 0; i < this.guaranteeCosts.length; i++) {
          num += this.guaranteeCosts[i]['QUANTITY']
        }
        this.guaranteeCosts["num"] = num;
        this.formateData();
      }
    });
    modal.present();
  }

  calculateSum() {
    this.sum = 0;
    this.fixedCosts.forEach(value => {
      this.sum = +(this.sum + +(value.PRICE * value.QUANTITY).toFixed(2)).toFixed(2);
    });
    this.diyCosts.forEach(value => {
      this.sum = +(this.sum + +(value.PRICE * value.QUANTITY).toFixed(2)).toFixed(2);

    });
    this.materialCosts.forEach(value => {
      this.sum = +(this.sum + +(value.PRICE * value.QUANTITY).toFixed(2)).toFixed(2);
    });
  }

  /**
   * 获取故障原因
   */
  getFaultCause() {
    this.worker.getFaultCause().then(
      value => {
        let data: any[] = value.data;
        data.forEach(v => {
          this.faultCause.push(v.GZYY);
        });

        if (this.faultCause.length != 0) {
          this.getMaintenancemMeasures();
        }

      }
    ).catch(e => {
      this.dialog.showAlert("加载故障原因错误");
    });


  }

  /**
   * 得到所有的维修措施
   */
  getMaintenancemMeasures() {

    this.faultCause.forEach(faultCause => {

      this.worker.getMaintenancemMeasures(faultCause).then(
        value => {
          let datas: any[] = value.data;
          this.maintenancemMeasures.set(faultCause, datas);
        }
      ).catch(
        e => {
          this.dialog.showAlert("获取维修措施错误");
        }
      );

    });
  }

  /**
   * 根据故障原因在页面展示对应的维修措施
   */
  loadMaintenancemMeasuresByFaultCause(faultCause?: any) {
    this.cacheFaultCause = faultCause||'';
    this.maintenancemMeasuresByFaultCause = this.maintenancemMeasures.get(faultCause)||[];
    console.log(this.maintenancemMeasuresByFaultCause);
  }

  /**
   * 获取结算对象
   */
  getSettlementObjects() {
    this.worker.getSettlementObjects(this.userInfo.GSXX01).then((data) => {
      this.settlementObjects = data.data;
    }).catch(() => {
    })
  }

  /**
   * 获取销售方式
   */
  getSalesMethods() {
    this.worker.getSalesMethods().then((data) => {
      this.salesMethods = data.data;
    }).catch(() => {
    })
  }
}
